package logic

import (
	"excel/dao/mysql"
	"fmt"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/xuri/excelize/v2"
)

func DeleteTempFiles() error {
	tempDir := "./temp"

	// 列出目录下的所有文件
	files, err := os.ReadDir(tempDir)
	if err != nil {
		return fmt.Errorf("error reading directory: %v", err)
	}

	// 删除每个文件
	for _, file := range files {
		if !file.IsDir() { // 确保不是目录
			filePath := filepath.Join(tempDir, file.Name())
			if err := os.Remove(filePath); err != nil {
				return fmt.Errorf("error deleting file %s: %v", filePath, err)
			}
		}
	}

	return nil
}

func GenerateImgExcel(Filename string, activities []mysql.Activity, imgs []string) error {
	currentDir, err := os.Getwd()
	if err != nil {
		println("Error getting current directory:", err)
	}
	println("Current directory:", currentDir)
	fmt.Println(imgs)
	// 创建 Excel 文件
	f := excelize.NewFile()
	// 定义工作表名
	sheetName := "Sheet1"
	// 创建一个工作表
	index, err := f.NewSheet(sheetName)
	if err != nil {
		fmt.Println("Error creating new sheet:", err)
		return err
	}
	// 设置列宽
	if err := f.SetColWidth(sheetName, "A", "F", 40); err != nil {
		fmt.Println("Error setting column width:", err)
		return err
	}

	// 设置行高
	for rowIndex := 1; rowIndex <= len(activities)+2; rowIndex++ { // +2 是因为有标题行
		if err := f.SetRowHeight(sheetName, rowIndex, 150); err != nil {
			fmt.Println("Error setting row height:", err)
			return err
		}
	}

	// 定义标题行
	headers := [][]string{
		{"title", "isRecommend", "manager", "activeDate", "images", "num"},
		{"*实践图集名称", "*是否推荐", "*发布单位", "*发布时间", "*图集", "点击量"},
	}

	// 添加标题行到工作表
	for rowIndex, headerRow := range headers {
		for colIndex, cell := range headerRow {
			cellCoord, err := excelize.CoordinatesToCellName(colIndex+1, rowIndex+1)
			if err != nil {
				fmt.Println("Error generating cell name:", err)
				return err
			}
			if err := f.SetCellValue(sheetName, cellCoord, cell); err != nil {
				fmt.Println("Error setting header data:", err)
				return err
			}
		}
	}

	// 填充图集数据
	for rowIndex, activity := range activities {
		// 根据规则生成 title
		titlePrefix := extractOrganizerPrefix(activity.Organizer)
		title := fmt.Sprintf("%s新时代文明实践活动——%s", titlePrefix, activity.Title)
		// 计算发布时间
		activeDate := calculateNewDate(activity.ActiveEndDate, 2)
		// 设置其他字段
		row := []interface{}{
			title,
			"否",
			titlePrefix,
			activeDate,
			"", // 替换为实际图片名
			"", // 点击量默认为空
		}

		for colIndex, value := range row {
			cell, err := excelize.CoordinatesToCellName(colIndex+1, rowIndex+3) // 从第三行开始写入数据
			if err != nil {
				fmt.Println("Error generating cell name:", err)
				return err
			}
			if err := f.SetCellValue(sheetName, cell, value); err != nil {
				fmt.Println("Error setting activity data:", err)
				return err
			}
		}

		// 添加图片
		if rowIndex < len(imgs) {
			imagePath := imgs[rowIndex] // 使用传入的图片路径
			//fmt.Println("Adding picture from:", imagePath) // 打印图片路径
			cell := fmt.Sprintf("E%d", rowIndex+3) // 假设每行数据对应到第E列
			//fmt.Println("cell", cell)
			//if _, err := os.Stat(imagePath); os.IsNotExist(err) {
			//	fmt.Println("Image file does not exist:", imagePath) // 确认文件存在
			//	return err
			//}
			if err := f.AddPicture(sheetName, cell, imagePath, &excelize.GraphicOptions{
				AutoFit:         true,
				Positioning:     "oneCell",
				LockAspectRatio: true, // 锁定宽高比
			}); err != nil {
				fmt.Println("Error adding picture:", err)
				return err
			}

			// 删除图片文件
			//if err := os.Remove(imagePath); err != nil {
			//	fmt.Println("Error deleting image file:", err)
			//}
		}
	}

	// 设置工作表为图集信息工作表
	f.SetActiveSheet(index)

	// 定义输出路径
	outputPath := "./uploadss/" + Filename
	// 保存文件
	if err := f.SaveAs(outputPath); err != nil {
		fmt.Println("Error saving Excel file:", err)
		return err
	}

	fmt.Println("Excel 文件已成功创建！")
	return nil
}

// 提取承办单位前缀
func extractOrganizerPrefix(organizer string) string {
	if strings.Contains(organizer, "社区") {
		return strings.Split(organizer, "社区")[0] + "社区"
	}
	if strings.Contains(organizer, "街道") {
		return strings.Split(organizer, "街道")[0] + "街道"
	}
	return organizer // 默认返回整个字符串
}

// 计算新日期
func calculateNewDate(dateStr string, daysOffset int) string {
	re := regexp.MustCompile(`(\d+)年(\d+)月(\d+)日(\d+):(\d+)`)
	matches := re.FindStringSubmatch(dateStr)
	if len(matches) != 6 {
		return ""
	}

	year, _ := strconv.Atoi(matches[1])
	month, _ := strconv.Atoi(matches[2])
	day, _ := strconv.Atoi(matches[3])
	hour, _ := strconv.Atoi(matches[4])
	minute, _ := strconv.Atoi(matches[5])

	t := time.Date(year, time.Month(month), day, hour, minute, 0, 0, time.Local)
	t = t.AddDate(0, 0, daysOffset) // 调整日期

	return fmt.Sprintf("%d年%d月%d日%d:%02d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute())
}
